package redis

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
)

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
func TestString() {
	redisClient := InitClient()

	ctx := context.Background()
	s := redisClient.Set(ctx, "s1", "1", 0)
	fmt.Println(s.Result())

	cmd := redisClient.Get(ctx, "s1")
	fmt.Println(cmd.Result())
}

func TestList() {
	redisClient := InitClient()
	ctx := context.Background()

	cmd := redisClient.LPush(ctx, "l1", "1")
	fmt.Println(cmd.Result())
	cmd = redisClient.LPush(ctx, "l1", "2")
	fmt.Println(cmd.Result())

	cmd1 := redisClient.LRange(ctx, "l1", 0, -1)
	fmt.Println(cmd1.Result())
}

func TestSet() {
	redisClient := InitClient()
	ctx := context.Background()

	cmd := redisClient.SAdd(ctx, "set1", "1")
	fmt.Println(cmd.Result())

	cmd = redisClient.SAdd(ctx, "set1", "2")
	fmt.Println(cmd.Result())

	cmd = redisClient.SAdd(ctx, "set1", "1")
	fmt.Println(cmd.Result())

	cmd1 := redisClient.SMembers(ctx, "set1")
	fmt.Println(cmd1.Result())
}

func TestZset() {
	redisClient := InitClient()
	ctx := context.Background()

	cmd := redisClient.ZAdd(ctx, "zset1", &redis.Z{1, "1"})
	fmt.Println(cmd.Result())

	cmd = redisClient.ZAdd(ctx, "zset1", &redis.Z{2, "2"})
	fmt.Println(cmd.Result())

	cmd1 := redisClient.ZRange(ctx, "zset1", 0, -1)
	fmt.Println(cmd1.Result())

	cmd2 := redisClient.ZRangeWithScores(ctx, "zset1", 0, -1)
	fmt.Println(cmd2.Result())
}

func TestHash() {
	redisClient := InitClient()
	ctx := context.Background()

	cmd := redisClient.HSet(ctx, "hash1", "name", "林芳伊", "age", "18")
	fmt.Println(cmd.Result())

	cmd = redisClient.HSet(ctx, "hash1", "addr", "北京")
	fmt.Println(cmd.Result())

	cmd1 := redisClient.HGetAll(ctx, "hash1")
	fmt.Println(cmd1.Result())
}

func TestPipeline() {
	ctx := context.Background()

	redisClient := InitClient()
	pipe := redisClient.Pipeline()

	pipe.Set(ctx, "count", "0", 0)
	pipe.IncrBy(ctx, "count", 1)
	pipe.IncrBy(ctx, "count", 2)
	pipe.Get(ctx, "count")

	results, _ := pipe.Exec(ctx)

	for _, result := range results {
		fmt.Println(result.Name())
	}
}

func TestPipeline2() {
	ctx := context.Background()

	redisClient := InitClient()
	redisClient.Pipelined(ctx, func(pipe redis.Pipeliner) error {
		pipe.IncrBy(ctx, "count", 3)
		pipe.IncrBy(ctx, "count", 2)

		pipe.Get(ctx, "count").Result()
		results, err := pipe.Exec(ctx)

		fmt.Println(results)
		return err
	})
}

func TestLua() {
	luaScript := `
local key = KEYS[1]
local a = 1
redis.call('hset', key, 'a', '1')
redis.call('hset', key, 'b', '2')
return redis.call('hgetall', key)
`
	redisClient := InitClient()
	cmd := redisClient.Eval(context.Background(), luaScript, []string{"lua1"})
	fmt.Println(cmd)
}
